package cn.edu.wzut.controller;


import cn.edu.wzut.mbp.entity.SysRole;
import cn.edu.wzut.mbp.service.ISysRoleService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/role")
public class RoleController {
    @Autowired
    private ISysRoleService roleService;


    @GetMapping
    public JsonResult<List<SysRole>> all() {
        List<SysRole> list = roleService.list();
        return new JsonResult<>(list);
    }


    //分页查询
    @GetMapping("/page")
    public  JsonResult<List<SysRole>> page(@RequestParam(defaultValue = "1") Integer currentPage){
        Page page = new Page(currentPage,10);
        IPage pageData = roleService.page(page, new QueryWrapper<SysRole>().orderByAsc("id"));
        return new  JsonResult(pageData);
    }

   //根据id查询数据
    @GetMapping("/{id}")
    public JsonResult<SysRole> get(@PathVariable("id") BigDecimal id) {
        SysRole sysRole = roleService.getById(id);
        return new JsonResult<>(sysRole);
    }

    //模糊查找
    @GetMapping("/search")
    public JsonResult<List<SysRole>> get(@RequestParam Map<String,Object> param) {
        QueryWrapper<SysRole> sysRoleQueryWrapper = new QueryWrapper<>();
        sysRoleQueryWrapper
                .like("role_Name", param.get("roleName"));
        List<SysRole> list = roleService.list(sysRoleQueryWrapper);
        return new JsonResult<>(list);
    }

    //保存
    @PostMapping
    public JsonResult<Object> save(@RequestBody SysRole sysRole) throws MyException {
        boolean b = roleService.saveOrUpdate(sysRole);
        if(b)
            return new JsonResult<>(0, "修改完成");
        else
            throw new MyException("修改失败");
    }
    //删除
    @DeleteMapping("/{id}")
    public JsonResult<Object> deleteOne(@PathVariable("id") BigDecimal id) throws MyException {
        boolean b = roleService.removeById(id);
        if(b)
            return new JsonResult<>(0, "删除完成");
        else
            throw new MyException("删除失败");
    }

}
